package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements IWechatService {
    private static final String OPENID_URL="https://api.weixin.qq.com/sns/jscode2session";
    private static final String TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token";
    private static final String PHONE_URL="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.secret}")
    private String secret;
    /**
     * 获取openid
     * @param code
     * @return
     */
    @Override
    public String getOpenid(String code) {
        Map<String,Object> paramp =new HashMap<>();
        paramp.put("appid",appid);
        paramp.put("secret",secret);
        paramp.put("js_code",code);
        paramp.put("grant_type","authorization_code");
        String result = HttpUtil.get(OPENID_URL, paramp);//调用hutool工具包的httputil请求
        JSONObject obj = JSONUtil.parseObj(result);//将请求结果转换成json对象
        Integer i =obj.getInt("errcode");//;获取json对象中errcode的值
        if(i==null||i==0){
            return obj.getStr("openid");
        }else{
            throw new RuntimeException("获取用户openid失败"+obj.toJSONString(1));
        }
    }

    /**
     * 获取手机号
     * @param detailCode
     * @return
     */
    @Override
    public String getPhone(String detailCode) {
        String token = getToken();
        Map<String,Object> paramp =new HashMap<>();
        paramp.put("code",detailCode);
        String result = HttpUtil.post(PHONE_URL+token, JSONUtil.toJsonStr(paramp));//将paramp转成json类型
        JSONObject obj = JSONUtil.parseObj(result);
        Integer i =obj.getInt("errcode");//;获取json对象中errcode的值
        if(i==null||i==0){
            return obj.getJSONObject("phone_info").getStr("phoneNumber");
        }else{
            throw new RuntimeException("获取用户手机号失败"+obj.toJSONString(1));
        }

    }

    /**
     * 获取token
     * @return
     */
    private String getToken() {
        Map<String,Object> paramp =new HashMap<>();
        paramp.put("appid",appid);
        paramp.put("secret",secret);
        paramp.put("grant_type","client_credential");
        String result = HttpUtil.get(TOKEN_URL, paramp);//调用hutool工具包的httputil请求
        JSONObject obj = JSONUtil.parseObj(result);//将请求结果转换成json对象
        Integer i =obj.getInt("errcode");//;获取json对象中errcode的值
        if(i==null||i==0){
            return obj.getStr("access_token");
        }else{
            throw new RuntimeException("获取微信token失败"+obj.toJSONString(1));
        }

    }
}